package com.ncloud.crm.service.impl;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.ncloud.common.enmus.ResultEnum;
import com.ncloud.common.exception.UserException;
import com.ncloud.crm.dubboservice.CustTrialService;
import com.ncloud.crm.entity.BsTrial;
import com.ncloud.crm.mapper.BsTrialMapper;
import com.ncloud.crm.service.BsTrialService;
import com.ncloud.param.service.SequenceService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * Created by shiqiang on 2017/6/13.
 */
@Service
public class BsTrialServiceImpl implements BsTrialService{
    @Autowired
    private BsTrialMapper bsTrialMapper;
    @Reference
    private SequenceService sequenceService;
    @Override
    public JSONObject insertTrial(JSONObject json) {
        //JSONObject result = new JSONObject();
        BsTrial bsTrial = JSON.parseObject(json.toJSONString(),BsTrial.class);
        validation(bsTrial);
        int num = bsTrialMapper.insertBsTrial(bsTrial);
        return JSON.parseObject(JSON.toJSONString(bsTrial, SerializerFeature.WriteMapNullValue));
    }

    private void validation(BsTrial bsTrial){
        bsTrial.setCreateTime(new Date());
        if(bsTrial.getTrialId() == null){
            Long id = sequenceService.getSequence("trial_id_seq");
            bsTrial.setTrialId(id);
        }
        if(StringUtils.isEmpty(bsTrial.getCompanyName())){
            throw new UserException(ResultEnum.PARAM_ERROR.getCode(),"【没有传companyName信息，请检查。】");
        }
        if(StringUtils.isEmpty(bsTrial.getContactName())){
            throw new UserException(ResultEnum.PARAM_ERROR.getCode(),"【没有传contactName信息，请检查。】");
        }
        if(StringUtils.isEmpty(bsTrial.getContactEmail())){
            throw new UserException(ResultEnum.PARAM_ERROR.getCode(),"【没有传contactEmail信息，请检查。】");
        }
        if(StringUtils.isEmpty(bsTrial.getContactPhone())){
            throw new UserException(ResultEnum.PARAM_ERROR.getCode(),"【没有传companyPhone信息，请检查。】");
        }
    }
}
